define(["jquery", "uiRegistry", "layui", "js/tracking/tracking-min", "js/tryon/swiper", "js/tryon/utils", "js/tracking/eye", "mage/translate"], function($, registry, _, track, Swiper) {
    'use strict';
    const option = {};
    var domain = window.location.origin;
    //显示模式
    let show_mode = 'product'
    // 弹窗 眼镜 鼠标判断是否按下
    let glassIsDown = false;
    var total = 0;
    let curData = [];
    let sex = '';
    let category = '';
    let MediaStreamTrack;
    var avatar = [
        {
            url: '/media/tryon/1.jpg',
            width: 103.377/344.59*480, // 144
            left: 111.274/344.59*480, // 155
            top: 108.41/344.59*480 // 151
        },
        {
            url: '/media/tryon/2.jpg',
            width: 86.1475/344.59*480, // 120
            left: 118.442156/344.59*480, // 165
            top: 100.505/344.59*480 // 140
        },
        {
            url: '/media/tryon/3.jpg',
            width: 99.07/344.59*480, // 138
            left: 124.55/344.59*480, // 173.5
            top: 114/344.59*480 // 158.75
        },
        {
            url: '/media/tryon/4.jpg',
            width: 103.377/344.59*480, // 144
            left: 125.6318/344.59*480, // 175
            top: 111.274/344.59*480 // 155
        },
        {
            url: '/media/tryon/5.jpg',
            width: 101.94/344.59*480, // 142
            left: 128.86/344.59*480, // 179.5
            top: 94.76/344.59*480 // 132.25
        },
        {
            url: '/media/tryon/6.jpg',
            width: 111.99/344.59*480, // 156
            left: 108.4/344.59*480, // 151
            top: 113.79/344.59*480 // 158.5
        },
        {
            url: '/media/tryon/7.jpg',
            width: 113.43/344.59*480, // 158
            left: 108.04/344.59*480, // 150.5
            top: 132.27/344.59*480 // 184.25

        },
        {
            url: '/media/tryon/8.jpg',
            width: 113.43/344.59*480, // 158
            left: 118.81/344.59*480, // 165.5
            top: 99.97/344.59*480 // 139.25
        },
        {
            url: '/media/tryon/9.jpg',
            width: 96.2/344.59*480, // 134
            left: 118.09/344.59*480, // 164.5
            top: 99.25/344.59*480 // 138.25
        },
        {
            url: '/media/tryon/10.jpg',
            width: 120.61/344.59*480, // 168
            left: 118.45/344.59*480, // 165
            top: 122.76/344.59*480 // 171
        }
    ]
    if(localStorage.getItem('first') === null) {
        localStorage.removeItem('avtarMedia')
        localStorage.setItem('first','end')
    }
    let modeMedia = localStorage.getItem('avtarMedia') ? JSON.parse(localStorage.getItem('avtarMedia')) : avatar;
    if(localStorage.getItem('avtarMedia') === null) {
        localStorage.setItem('avtarMedia',JSON.stringify(modeMedia))
    }
    let currentAvtar = 0
    let glasses = ['/media/tryon/glasses/1.png','/media/tryon/glasses/2.png','/media/tryon/glasses/3.png']
    let swiperHead="";
    let alertswiperHead="";
    let eyeOptions = [];
    // 弹窗 眼镜 位置
    let glassX=0;
    let glassY=0;
    let glassL=0;
    let glassT=0;
    let swiperGlasses="";
    let btn = document.querySelector('.showMore');
    // 判断显示pc端or移动端的head
    var _isPc=isPC();
    //添加切换显示模式按钮
    let mode_html = `<div class="mode-box"><div class="mode-btn show-product mode-btn-status" data-type="product">${$.mage.__('Front Show')}</div><div class="mode-btn try" data-type="tryon">${$.mage.__('Try Online')}</div></div>`
    if(_isPc) {
        $(".productFilter").append($(mode_html))
    }
    else {
        $(mode_html).insertAfter($(".productFilter"))
    }
    //取消try on模式
    $(document).on("click",'.mode-box .show-product',function () {
        $('.try').removeClass("mode-btn-status")
        $(this).addClass("mode-btn-status")
        if(show_mode != 'product') {
            $("#productList").html("")
            $(".product-try-on-list").remove()
            show_mode = 'product'
            productConfig.page = 0
            curData = []
            btn.click()
        }
    })
    $(document).on("click",'.mode-box .try',function () {
        $('.show-product').removeClass("mode-btn-status")
        $(this).addClass("mode-btn-status")
        if(show_mode === 'product') {
            if($("#tempImg").length === 0) {
                var temImg = new Image();
                temImg.src = currentAvtar
                temImg.style.width = 486+'px'
                temImg.id = 'tempImg'
                temImg.style.position = "absolute"
                temImg.style.left = "-10000px"
                document.querySelector('.page-wrapper').appendChild(temImg)
            }
            $("#productList").html("")
            addSwiper()
            show_mode = 'tryon'
            curData = []
            productConfig.page = 0
            btn.click()
        }
    })
    // 判断是否是pc端打开
    function isPC() {
        var userAgentInfo = navigator.userAgent;
        var Agents = ["Android", "iPhone","SymbianOS", "Windows Phone","iPad", "iPod"];
        var flag = true;
        for (var v = 0; v < Agents.length; v++) {
            if (userAgentInfo.indexOf(Agents[v]) > 0) {
                flag = false;
                break;
            }
        }
        return flag;
    }
    // 将别的类型的数据，修改为number
    function changeNumber(text){
        let _text=text.substring(0,text.length-2);
        _text=parseFloat(_text);
        return _text;
    }
    //关闭tryon
    $(document).on("click",'.try-on-box .common-alert-close',function () {
        $(".try-on-box").remove()
    })
    // 获取url中的参数
    function GetUrlParam(paraName) {
        var url = document.location.toString();
        var arrObj = url.split("?");
        if (arrObj.length > 1) {
            var arrPara = arrObj[1].split("&");
            var arr;
            for (var i = 0; i < arrPara.length; i++) {
                arr = arrPara[i].split("=");
                if (arr != null && arr[0] == paraName) return arr[1];
            }
            return "";
        } else {
            return "";
        }
    }
    sex = GetUrlParam('sex');
    category = GetUrlParam('category');
    // 初始化配置
    const productConfig = {
        category: category,
        sex: sex,
        page: 1,
        size: 12
    };
    // 如果列表id不存在就往首页走
    if (!category) location.href = '/'
    load_data(productConfig);
    // 页面交互逻辑
    class productFun {
        constructor() {}
        initClick(option, data) {
            let self = this;
            var _option = {
                productionListEle: option.productionListEle,
                clickEle: option.clickEle,
                changeEle: option.changeEle,
                clickClass: option.clickClass,
                changeClass: option.changeClass,
                _favourites: option._favourites
            };
            const productionList_li = document.querySelectorAll(_option.productionListEle);
            for (let j = 0; j < productionList_li.length; j++) {
                const _clickEle = productionList_li[j].querySelectorAll(_option.clickEle);
                const __favourites = productionList_li[j].querySelector(_option._favourites);
                // 初始化状态
                self.switchLi(0, _option, productionList_li[j]);
                if(show_mode != 'product') {
                    setTimeout(function(){
                        autoMatch(currentAvtar,$(".productionList_li").eq(j).find(".productionListActive").eq(0).find(".product-try-right-head").attr("id"))
                    },500);
                }
                for (let i = 0; i < _clickEle.length; i++) {
                    (function(i) {
                        _clickEle[i].addEventListener('click', function(e) {
                            e.preventDefault();
                            self.switchLi(i, _option, productionList_li[j]);
                            $(this).parents(".productionList_li_content").prev(".productionList_img").find(".productionList_img_li").each(function () {
                                var temIndex = $(this).index()
                                if(temIndex === i) {
                                    $(this).find("img").each(function () {
                                        if($(this).attr("src") === '#') {
                                            $(this).attr("src",$(this).attr("data-src"))
                                        }
                                    })
                                    if(show_mode != 'product') {
                                        setTimeout(function(){
                                            autoMatch(currentAvtar,$(this).find(".product-try-right-head").attr("id"))
                                        },500);
                                    }
                                }
                            })
                        }, false);
                    })(i)
                }
                __favourites.addEventListener('click', function(e) {
                    e.preventDefault();
                    self.addFavourites(j, curData);
                }, false)
            }
        }
        // 去掉样式的小数点
        _returnClass(_class) {
            const reg = /^\.?/g;
            let _Class = _class.replace(reg, "");
            return _Class
        }
        switchLi(index, _option, ele) {
            let self = this;
            const _clickEle = ele.querySelectorAll(_option.clickEle);
            const _changeEle = ele.querySelectorAll(_option.changeEle);
            let _clickClass = self._returnClass(_option.clickClass);
            let _changeClass = self._returnClass(_option.changeClass);
            let imgIndex = 0;

            if (_clickEle && _clickEle.length && _changeEle && _changeEle.length) {
                for (let i = 0; i < _clickEle.length; i++) {
                    if (_clickEle[i]) _clickEle[i].classList.remove(_clickClass);
                    if (_changeEle[i]) {
                        _changeEle[i].classList.remove(_changeClass);
                        _changeEle[i].querySelectorAll("img")
                        if (_clickEle[index].dataset.color === _changeEle[i].dataset.color) imgIndex = i;
                    }    
                }
                if (_clickEle[index]) _clickEle[index].classList.add(_clickClass);
                if (_changeEle[imgIndex]) {
                    _changeEle[imgIndex].classList.add(_changeClass);
                    //  判断当前索引的图片src是否存在地址，不存在就获取data-src的图片进行赋值
                    let img = _changeEle[imgIndex].children[0];
                    let src = img.getAttribute('src')
                    if (src === '#') {
                        img.setAttribute('src', img.dataset.src)
                    }
                };
            }
        }
        addFavourites(index, data) {
            let wishData = JSON.parse(localStorage.getItem('wishData'));
            let self = this;

            if (wishData && wishData.length) {
                let isAdd = false;
                for (let i = 0; i < wishData.length; i++) {
                    let _wishData = wishData[i];
                    if (_wishData.id === data[index].id) {
                        isAdd = true;
                        wishData.splice(i, 1);
                        $('._favourites .glyphicon').eq(index).removeClass('glyphicon-heart');
                        $('._favourites .glyphicon').eq(index).addClass('glyphicon-heart-empty');
                        localStorage.setItem('wishData', JSON.stringify(wishData));
                        registry.get('heartlist').delete()
                        return
                    }
                }
                if (!isAdd) {
                    wishData.push(data[index]);
                    localStorage.setItem('wishData', JSON.stringify(wishData));
                    registry.get('heartlist').update()
                    $('._favourites .glyphicon').eq(index).removeClass('glyphicon-heart-empty');
                    $('._favourites .glyphicon').eq(index).addClass('glyphicon-heart');
                }
            } else {
                let tempArray = [];
                tempArray.push(data[index]);
                localStorage.setItem('wishData', JSON.stringify(tempArray));
                // 更新爱心列表
                registry.get('heartlist').update();
                $('._favourites .glyphicon').eq(index).removeClass('glyphicon-heart-empty');
                $('._favourites .glyphicon').eq(index).addClass('glyphicon-heart');
            }

            /** wishListener */
            document.addEventListener('removeWishItem', function(e) {
                if (data[index].id == e.detail.id) {
                    $('._favourites .glyphicon').eq(index).removeClass('glyphicon-heart');
                    $('._favourites .glyphicon').eq(index).addClass('glyphicon-heart-empty');
                }
            })
            /** wishListener end */
        }
    }
    //渲染swiper
    function addSwiper() {
        let _html = '';
        _html += `<div class="product-try-on-list">`
        if(_isPc) {
            _html += `<div class="btn-wrapper try_Online_upload">
                            <div class="note-info">${$.mage.__('Upload your picture or use any of our models')}</div>
                            <div class="try-right-upload-btn">
                            <div class="common-btn"><i></i>${$.mage.__('Upload Your Photo')}</div>
                            </div>
                            <div class="use-webcam" id="use-webcam"><i></i>${$.mage.__('Use Your Webcam')}</div>
                        </div>`
        }
        else {
            _html += `<div class="try-right-upload-btn">
                        <div class="note-info">${$.mage.__('Upload your picture or use any of our models')}</div>
                        <div class="common-btn"><i></i>${$.mage.__('Upload Your Photo')}</div>
                        <div class="use-webcam" id="use-webcam"><i></i>${$.mage.__('Use Your Webcam')}</div>
                </div>`
        }
        _html += `<div class="swiper-container swiper-head"><div class="swiper-wrapper">`
        modeMedia.forEach(item => {
            _html+=`<div class="swiper-slide">
                        <img src="`+item.url+`" class="swiper-slide-img"/>
                        </div>`
        })
        _html += `</div><div class="swiper-button-next"></div><div class="swiper-button-prev"></div></div>`
        _html += `<div class="try-right-file-btn">
                <form method="post" enctype="multipart/form-data" class="zxtdcyy_upload_file_form" id="uploadForm">
                <input type="file" class="try-right-file" accept="image/*" name="image" id="pic_img" style="display: none"/>
                </form>
                </div></div>`
        $(_html).insertBefore($("#productList"))
        $(".try-right-file").on("change",function () {
            var file = this.files[0] ? this.files[0] : null;
            if(null == file){
                return false;
            }
            var file_reader = new FileReader();
            file_reader.onload = (function(){
                var image_url = this.result;        // 这是图片的路径
                _isPc=isPC()
                if(_isPc) {
                    getEyePositionPc(image_url)
                }
                else {
                    getEyePositionMobile(image_url)
                }
            });
            file_reader.readAsDataURL(file);
        })
        // pc端 try on 头像轮播图
        swiperHead = new Swiper('.swiper-head', {
            slidesPerView: 4,
            spaceBetween: 5,
            navigation: {
                nextEl: '.swiper-head .swiper-button-next',
                prevEl: '.swiper-head .swiper-button-prev',
            },
        });
        $.ajax({
            url: domain +'/rest/V1/maijindou/catalog/upimage',
            type: 'GET',
            cache: false,
            dataType: 'json',
            processData: false,
            contentType: false
        }).done(function(res){
            $.each(res.data,function(i,item){
                var url = item;
                let _htmlstr=`<i class="swiper-slide-img-close"></i>
                <img src="`+url+`" class="swiper-slide-img upload_self">`
                swiperHead.prependSlide([
                    '<div class="swiper-slide"> ' + _htmlstr + '</div>'
                ]);
            });
            swiperHead.slideTo(0, 0);
            $('.swiper-head .swiper-slide').eq(0).trigger('click');
        }).fail(function(res){
            console.log(res);
        });
    }
    function b64toBlob(b64Data, contentType='', sliceSize=512) {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            const slice = byteCharacters.slice(offset, offset + sliceSize);

            const byteNumbers = new Array(slice.length);
            for (let i = 0; i < slice.length; i++) {
                byteNumbers[i] = slice.charCodeAt(i);
            }

            const byteArray = new Uint8Array(byteNumbers);

            byteArrays.push(byteArray);
        }

        const blob = new Blob(byteArrays, {type: contentType});
        return blob;
    }
    //弹窗使用摄像头
    $(document).on('click','#alert-use-webcam',function(e){
        webcam()
    })
    //使用摄像头
    $(document).on('click','#use-webcam',function(e){
        webcam()
    })
    //webcam 模板
    function webcam() {
        let html = `<div class="alert-window try-on-box webcam-box" id="eye-window"><div class="try-content"><div class="try-left-box">`
        html += `<div class="title-box">
                    <div class="title">${$.mage.__('EYECEDAR')}</div>
                    <div class="sub-title">${$.mage.__('Try on glasses')}</div>
                    <div class="pd-box" style="display: flex;margin-top: 20px;">
                        <label class="label" style="display: block;margin-right: 10px">${$.mage.__('PD')}</label>
                        <input type="number" class="pd-text" value="62">
                    </div>
                </div>
                </div>
                <div class="try-right-box">
                <i class="eye-close"></i>
                <div class="position-img-box" id="canvas-box">
                    <video id="video" width="480" height="480" preload autoplay loop muted playsinline webkit-playsinline="true" ></video>
                    <canvas id="eye-position" width="480" height="480" class="eye-position" style="display: none"></canvas>
                    <div class="red-btn left-eye" id="left-eyes"></div>
                    <div class="red-btn right-eye" id="right-eyes"></div>
                </div>
                <div class="toolbar-box">
                    <button id="start">${$.mage.__('RETAKE')}</button>
                    <button id="snap">${$.mage.__('webcam')}</button>
                    <button type="button" class="try-glass" id="apply" style="display: none">${$.mage.__('TRY ON GLASSES')}</button>
                </div>
                </div>
                </div>
                </div>`
        $("body").append(html)
        var canvas = document.getElementById('eye-position'),
            context = canvas.getContext('2d'),
            apply = document.getElementById("apply"),
            video = document.getElementById("video"),
            snap = document.getElementById("snap"),
            box = document.getElementById("canvas-box"),
            start = document.getElementById("start");
        setTimeout(function () {
            start.click()
        },500)
        start.addEventListener('click', function () {
            video.classList.remove('hide')
            canvas.classList.remove(('show'))
            box.classList.remove('move')
            if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia ({
                    video: { width: 480, height: 480 },
                    audio: false
                }).then(function (stream) {
                    context.clearRect(0, 0,480,480)
                    snap.style.display = 'inline-block'
                    apply.style.display = 'none'
                    start.style.display = 'none'
                    if ("srcObject" in video) {
                        video.srcObject = stream
                    } else {
                        video.src = window.URL.createObjectURL(stream)
                    }
                    MediaStreamTrack = stream.getTracks()[0];
                    video.onloadedmetadata = function (e) {
                        video.play();
                        var tracker = new tracking.ObjectTracker(['eye']);
                        tracker.setInitialScale(4);
                        tracker.setStepSize(2);
                        tracker.setEdgesDensity(0.1);
                        tracking.track('#video', tracker);
                    }
                })
                    .catch(function (err) {
                        console.log('err', err)
                        alert($.mage.__('你的设备没有摄像头'))
                        close.click()
                    })
            }
            else {
                alert($.mage.__('你的设备没有摄像头'))
                $(".eye-close").click()
            }
        });
        snap.addEventListener('click', function () {
            canvas.classList.add("show")
            video.classList.add("hide")
            box.classList.add('move')
            start.innerHTML = $.mage.__("重拍")
            snap.style.display = 'none'
            apply.style.display = 'inline-block'
            start.style.display = 'inline-block'
            context.drawImage(video, 0, 0,480,480);
            MediaStreamTrack && MediaStreamTrack.stop();
        });
        mouseDomEventEyeByPc()
    }
    // ================== 添加 下载图片 ================== //
    var jsonstr = [];
    var jsoni = 0;
    // 添加背景人物图片
    $(document).on('click','.try-right-upload-btn .common-btn',function(e){
        $('.try-right-file').click();
    })
    // 添加背景人物图片
    $(document).on('click','.try-alert-right-upload-btn .common-alert-btn',function(e){
        $('.try-alert-right-file').click();
    })
    // 添加人脸
    $(document).on("click",".try-glass",function () {
        var _isP
        let canvas = document.getElementById('eye-position');
        let ctx = canvas.getContext('2d');
        var dataurl =  canvas.toDataURL("image/jpeg");
        var block = dataurl.split(";");
        const contentType = block[0].split(":")[1];// In this case "image/jpeg"
        const realData = block[1].split(",")[1];//
        var blob = b64toBlob(realData, contentType);
        const formData = new FormData();
        formData.append('blob',blob);
        var pid = Number($(".pd-text").val().replace(/\d/g, ""));
        if(pid > 74 || pid < 54) {
            pid = 62
        }
        var r_width = 2*pid
        var canvas_w = $("#eye-position").width()
        var left = $("#left-eyes").position().left+15-($("#right-eyes").position().left - $("#left-eyes").position().left)/2
        left = left*480/canvas_w
        var max = $("#right-eyes").position().top > $("#left-eyes").position().top ? $("#right-eyes").position().top : $("#left-eyes").position().top
        var top = max+15-($("#right-eyes").position().left - $("#left-eyes").position().left)/4
        top = top*480/canvas_w
        var width = r_width*($("#right-eyes").position().left - $("#left-eyes").position().left)/pid
        width = width*480/canvas_w
        $.ajax({
            url: domain +'/rest/V1/maijindou/catalog/upimage',
            type: 'POST',
            cache: false,
            data: formData,
            processData: false,
            contentType: false
        }).done(function(res) {
            if($("#try-on-box").length > 0) {
                let _html=`<i class="swiper-slide-img-close"></i>
            <img src="`+res.data.pic_img.replace('/pub','')+`" class="swiper-slide-img upload_self">`;
                if(show_mode != 'product') {
                    swiperHead.prependSlide([
                        '<div class="swiper-slide"> ' + _html + '</div>'
                    ]);
                }
                alertswiperHead.prependSlide([
                    '<div class="swiper-slide"> ' + _html + '</div>'
                ]);
                alertswiperHead.slideTo(0, 0);
                modeMedia.unshift({url:res.data.pic_img.replace('/pub',''),left: left,top: top,width: width});
                localStorage.setItem('avtarMedia',JSON.stringify(modeMedia))
                $('.swiper-alert-head .swiper-slide').eq(0).click();
                $('.try-alert-right-file').val('');
                _isPc=isPC()
                if(_isPc) {
                    mouseDomEventGlassByPc()
                }
                else {
                    mouseDomEventGlassByMobile();
                }
            }
            else {
                let _html=`<i class="swiper-slide-img-close"></i>
            <img src="`+res.data.pic_img.replace('/pub','')+`" class="swiper-slide-img upload_self">`
                swiperHead.prependSlide([
                    '<div class="swiper-slide"> ' + _html + '</div>'
                ]);
                swiperHead.slideTo(0, 0);
                currentAvtar = res.data.pic_img.replace('/pub','')
                modeMedia.unshift({url:res.data.pic_img.replace('/pub',''),left: left,top: top,width: width});
                localStorage.setItem('avtarMedia',JSON.stringify(modeMedia))
                $('.swiper-head .swiper-slide').eq(0).click();
                $('.try-right-file').val('');
            }
            $("#eye-window").remove()
        }).fail(function(res) {
            console.log(res);
        });
    })
    //关闭定点弹窗
    $(document).on("click",".eye-close",function () {
        $("#eye-window").remove()
        if($("#try-on-box").length > 0) {
            $('.try-alert-right-file').val('');
        }
        else {
            $('.try-right-file').val('');
        }
        if(MediaStreamTrack) {
            MediaStreamTrack.stop();
        }
    })
    // 上传的图片过大 报错信息
    function getBigImageAlert(){
        let _html="";
        _html+=`<div class="common-alert error-box">
                    <div class="error-size">
                    <i class="error-close"></i>
                    <p class="error-title">${$.mage.__('It seems that the image you uploaded is too large.')}</p>
                    <p class="error-message">${$.mage.__("Please add a photo(JPEG or PNG) of yourself no larger than 20MB")}</p>
                    </div>
                    </div>`
        $('body').append(_html);
    }
    // 删除自定义上传的背景人物图片
    $(document).on('click','.swiper-head .swiper-slide-img-close',function(){
        let _dom=$(this).parent('.swiper-slide');
        let _index = $(".swiper-head .swiper-slide").index(_dom);
        // ----- 添加close备注(防止头像切换再次操作) ----- //
        $(this).attr('date-delete',true);
        // ----- 删除dom ----- //
        swiperHead.removeSlide(_index);
        // ----- 处理新dom ----- //
        // 当前被选中的模特列表图
        let _activeMenu=$(this).next('img').attr('src');
        let _activeModel=$('img[id^="headCanvas-"]').eq(0).attr('src');
        let _nextDom="";
        if(_index==0){
            swiperHead.slideTo(0, 0);
            _nextDom= (_activeMenu===_activeModel) ? $('.swiper-head .swiper-slide').eq(0) : "";
        }else {
            swiperHead.slideTo(_index, 0);
            _nextDom= (_activeMenu===_activeModel) ? $('.swiper-head .swiper-slide').eq(_index) : "";
        }
        modeMedia.splice(_index,1);
        localStorage.setItem('avtarMedia',JSON.stringify(modeMedia))
        currentAvtar = _index
        autoMatch(_index)
    })
    // try on 删除自定义上传的背景人物图片
    $(document).on('click','.swiper-alert-head .swiper-slide-img-close',function(){
        let _dom=$(this).parent('.swiper-slide');
        let _index = $(".swiper-alert-head .swiper-slide").index(_dom);
        // ----- 添加close备注(防止头像切换再次操作) ----- //
        $(this).attr('date-delete',true);
        // ----- 删除dom ----- //
        if(show_mode != 'product') {
            swiperHead.removeSlide(_index);
        }
        alertswiperHead.removeSlide(_index);
        // ----- 处理新dom ----- //
        // 当前被选中的模特列表图
        let _activeMenu=$(this).next('img').attr('src');
        let _activeModel=$('#headCanvas').eq(0).attr('src');
        let _nextDom="";
        if(_index==0){
            if(show_mode != 'product') {
                swiperHead.slideTo(0, 0);
            }
            alertswiperHead.slideTo(0, 0);
            _nextDom= (_activeMenu===_activeModel) ? $('.swiper-alert-head .swiper-slide').eq(0) : "";
        }else {
            if(show_mode != 'product') {
                swiperHead.slideTo(_index, 0);
            }
            alertswiperHead.slideTo(_index, 0);
            _nextDom= (_activeMenu === _activeModel) ? $('.swiper-alert-head .swiper-slide').eq(_index) : "";
        }
        if(_nextDom){
            // 获取下一个dom的img路径
            let _nextImg=_nextDom.children('.swiper-slide-img').attr('src');
        }
        modeMedia.splice(_index,1);
        localStorage.setItem('avtarMedia',JSON.stringify(modeMedia))
        currentAvtar = _index
        alertAutoMatch(_index,'headCanvas')
    })
    //建立一個可存取到文件url的函数
    function getObjectURL(file) {
        var url = null ;
        // 下面函数执行的效果是一样的，只是需要针对不同的浏览器执行不同的 js 函数而已
        if (window.createObjectURL!=undefined) { // basic
            url = window.createObjectURL(file) ;
        } else if (window.URL!=undefined) { // mozilla(firefox)
            url = window.URL.createObjectURL(file) ;
        } else if (window.webkitURL!=undefined) { // webkit or chrome
            url = window.webkitURL.createObjectURL(file) ;
        }
        return url ;
    }
    // ================== 头像切换 眼镜切换 ================== //
    // 头像轮播图 切换
    $(document).on('click','.swiper-head .swiper-slide',function(){
        if($(this).find("img").attr("src") != $('canvas[id^="headCanvas-"]').eq(0).attr('data-url')) {
            var num = $(this).index()
            let _img=$(this).children('img').attr('src');
            $(this).addClass('swiper-slide-active').siblings().removeClass('swiper-slide-active');
            if($(this).children('.swiper-slide-img-close').length>0){
                let _delete=$(this).children('.swiper-slide-img-close').attr('date-delete');
                if(!_delete){
                    currentAvtar = num
                    autoMatch(num)
                }
            }else{
                currentAvtar = num
                autoMatch(num)
            }
        }
    })
    // try on 头像轮播图 切换
    $(document).on('click','.swiper-alert-head .swiper-slide',function(){
        if($(this).find("img").attr("src") != $('#headCanvas').eq(0).attr('src')) {
            var num = $(this).index()
            $(this).addClass('swiper-slide-active').siblings().removeClass('swiper-slide-active');
            if($(this).children('.swiper-slide-img-close').length>0){
                let _delete=$(this).children('.swiper-slide-img-close').attr('date-delete');
                if(!_delete){
                    alertAutoMatch(num,'headCanvas')
                }
            }else{
                alertAutoMatch(num,'headCanvas')
            }
        }
    })
    //pc 眼镜轮换
    $(document).on("click",'.glasses-list .glasses-item .glasses-item-img',function () {
        if(!$(this).parent(".glasses-item").hasClass("active")) {
            $(this).parent(".glasses-item").addClass("active").siblings().removeClass('active');
            let _img=$(this).attr('src');
            $("#glassesMove").attr("src",_img)
            alertAutoMatch($(".try-on-box .swiper-slide-active").index(),'headCanvas')
        }
    })
    // 移动端 眼镜切换
    $(document).on('click','.swiper-glasses .swiper-slide',function(){
        if(!_isPc){
            let _img=$(this).children('img').attr('src');
            if($("#glassesMove").attr("src") != _img) {
                $("#glassesMove").attr("src",_img)
                alertAutoMatch($(".try-on-box .swiper-slide-active").index(),'headCanvas')
            }
        }
    })
    //try on
    $(document).on("click",'.productionList_li_content .tryon',function () {
        _isPc = isPC()
        if(_isPc) {
            getAlertInfoByPc($(this))
        }
        else {
            getAlertInfoByMobile($(this))
        }
        return false
    })
    //获取pc try on 弹窗
    function getAlertInfoByPc(obj) {
        let tempGlasses = []
        obj.parent(".btn-wrapper").prev(".glasses-box").find("li").each(function () {
            tempGlasses.push($(this).find("img").attr('data-src'))
        })
        let windowHtml = `<div class="alert-window try-on-box" id="try-on-box"><div class="try-content"><div class="try-left-box"><ul class="glasses-list">`
        tempGlasses.forEach((item,index) => {
            if(index==0){
                windowHtml+=`<li class="glasses-item active">`
            }else{
                windowHtml+=`<li class="glasses-item">`
            }
            windowHtml+=`<img src="`+item+`" class="glasses-item-img"/></li>`
        })
        windowHtml += `</ul>
                <div class="title-box">
                    <div class="title">${$.mage.__('EYECEDAR')}</div>
                    <div class="sub-title">${$.mage.__('Try on glasses')}</div>
                </div>
                <div class="note-info">${$.mage.__('Notes on using your photos')}<span class="help-icon">?</span></div>
                </div>
                <div class="try-right-box">
                <i class="common-alert-close"></i>
                <div class="try-right-head-box">
                <img id="headCanvas" class="try-right-head" src="${modeMedia[0]}" />
                <img class="try-head-loading" src="/media/wysiwyg/static_page_resource/common/Spin-1s-200px.gif" />
                <img src="${tempGlasses[0]}" id="glassesMove" class="try-right-glasses none" />
                <div class="try-right-head-tool""><img src="/media/tryon/tryicon/rotate.png" class="none" id="tool_img"></div>
                </div>
                <div class="toolbar">
                <div class="try-scale">
                <i class="try-left-icon icon-narrow"></i>
                <div class="try-swiper-box">
                <input type="range" value="50" min="0" max="100" step="0.1" class="try-swiper-input">
                </div>
                <i class="try-left-icon icon-add"></i>
                </div>
                <div class="try-rotate">
                <i class="try-left-icon icon-turn-left"></i>
                <div class="try-swiper-box">
                <input type="range" value="50" min="0" max="100" step="0.1" class="try-swiper-input">
                </div>
                <i class="try-left-icon icon-turn-right"></i>
                </div>
                </div>
                <div class="swiper-alert-container swiper-alert-head">
                    <div class="swiper-wrapper">`
        modeMedia.forEach(item => {
            windowHtml+=`<div class="swiper-slide">
                        <img src="`+item.url+`" class="swiper-slide-img"/>
                        </div>`
        })
        windowHtml+=`</div>
                    <div class="swiper-button-next"></div>
                    <div class="swiper-button-prev"></div>
                    </div>`
        windowHtml+=`<div class="alert-btn-wrapper">
                        <div class="try-alert-right-upload-btn">
                        <div class="common-alert-btn"><i></i>${$.mage.__("Upload Your Photo")}</div>
                        </div>
                        <div class="alert-use-webcam" id="alert-use-webcam"><i></i>${$.mage.__("Use Your Webcam")}</div>
                    </div>`
        windowHtml+=`<div class="try-alert-right-file-btn">
                    <form method="post" enctype="multipart/form-data" class="zxtdcyy_upload_file_form" id="uploadForm-alert">
                    <input type="file" class="try-alert-right-file" accept="image/*" name="image"  id="pic_alert_img"/>
                    </form>
                    </div>
                </div></div></div>`
        $("body").append(windowHtml)
        // 等待头像图片渲染完成在显示旋转图标
        $("#headCanvas").load(function() {
            $("#tool_img").removeClass("none")
            $(".try-head-loading").addClass("none");
            $("#glassesMove").removeClass("none")
        })
        alertswiperHead = new Swiper('.swiper-alert-head', {
            slidesPerView: 6,
            spaceBetween: 5,
            navigation: {
                nextEl: '.swiper-alert-head .swiper-button-next',
                prevEl: '.swiper-alert-head .swiper-button-prev',
            },
        });
        $(".try-alert-right-file").on("change",function () {
            var file = this.files[0] ? this.files[0] : null;
            if(null == file){
                return false;
            }
            var file_reader = new FileReader();
            file_reader.onload = (function(){
                var image_url = this.result;        // 这是图片的路径
                _isPc=isPC()
                if(_isPc) {
                    getEyePositionPc(image_url)
                }
                else {
                    getEyePositionMobile(image_url)
                }
            });
            file_reader.readAsDataURL(file);
        })
        mouseDomEventGlassByPc()
        mouseDomEventBySlider()
        setTimeout(function(){
            alertAutoMatch(0,'headCanvas');
        },500)
    }
    // 获取mobile try on 弹窗
    function getAlertInfoByMobile(obj) {
        let _html='';
        let tempGlasses = []
        obj.parent(".btn-wrapper").prev(".glasses-box").find("li").each(function () {
            tempGlasses.push($(this).find("img").attr('data-src'))
        })
        _html+=`<div class="alert-window try-on-box" id="try-on-box" style="overflow:auto;">
            <div class="try-content">
            <div class="note-info">${$.mage.__('Notes on using your photos')}<span class="help-icon">?</span></div>
            <i class="common-alert-close"></i>
            <div class="try-right-head-box">
            <img id="headCanvas" class="try-right-head" src="${modeMedia[0]}">
            <img src="${tempGlasses[0]}" id="glassesMove" class="try-right-glasses" />
            <div class="try-right-head-tool">
            <img src="/media/tryon/tryicon/rotate.png">
            </div>
            <div class="try-base-tool">
            <div class="try-base-tool-left">
            <i class="try-icon icon-add"></i>
            <i class="try-icon icon-narrow"></i>
            <i class="try-icon icon-turn-right"></i>
            <i class="try-icon icon-turn-left"></i>
            <div class="common-clear"></div>
            </div>
            <div class="try-base-tool-right">
            <i class="try-icon icon-arrow-up"></i>
            <i class="try-icon icon-arrow-left"></i>
            <i class="try-icon icon-arrow-right"></i>
            <i class="try-icon icon-arrow-down"></i>
            <div class="common-clear"></div>
            </div>
            </div>
            </div>
            <div class="swiper-container swiper-glasses">
            <div class="swiper-wrapper">`
        tempGlasses.forEach(item => {
            _html+=`<div class="swiper-slide">
                <img src="`+item+`" class="swiper-slide-img"/>
                </div>`
        })
        _html+=`</div>
            <div class="swiper-button-next"></div>
            <div class="swiper-button-prev"></div>
            </div>
            <div class="swiper-alert-container swiper-alert-head">
            <div class="swiper-wrapper">`
        modeMedia.forEach(item => {
            _html+=`<div class="swiper-slide">
                        <img src="`+item.url+`" class="swiper-slide-img"/>
                        </div>`
        })
        _html+=`</div>
            <div class="swiper-button-next"></div>
            <div class="swiper-button-prev"></div>
            </div>
            <div class="try-right-upload-btn">
            <div class="common-btn"><i></i>${$.mage.__("Upload Your Photo")}</div>
            </div>
            <div class="try-right-file-btn">
            <form method="post" enctype="multipart/form-data" class="zxtdcyy_upload_file_form" id="uploadForm-alert">
                <input type="file" class="try-alert-right-file" accept="image/*" name="image"  id="pic_alert_img"/>
            </form>
            </div>
            </div>
            </div>
            </div>`
        $('body').append(_html);
        // 移动端 try on 眼镜轮播图
        swiperGlasses = new Swiper('.swiper-glasses', {
            slidesPerView: 3.7,
            spaceBetween: 15,
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
        });
        // 移动端 try on 头像轮播图
        alertswiperHead = new Swiper('.swiper-alert-head', {
            slidesPerView: 5.5,
            spaceBetween: 8,
            navigation: {
                nextEl: '.swiper-alert-head .swiper-button-next',
                prevEl: '.swiper-alert-head .swiper-button-prev',
            },
        });
        $(".try-alert-right-file").on("change",function () {
            var file = this.files[0] ? this.files[0] : null;
            if(null == file){
                return false;
            }
            var file_reader = new FileReader();
            file_reader.onload = (function(){
                var image_url = this.result;        // 这是图片的路径
                _isPc=isPC()
                if(_isPc) {
                    getEyePositionPc(image_url)
                }
                else {
                    getEyePositionMobile(image_url)
                }
            });
            file_reader.readAsDataURL(file);
        })
        // 拖拽 鼠标事件
        mouseDomEventGlassByMobile();
        // 自动佩戴眼镜
        setTimeout(function(){
            alertAutoMatch(0,'headCanvas');
        },500)
    }
    // 获取pc眼睛定点
    function getEyePositionPc(url) {
        let windowHtml = `<div class="alert-window try-on-box" id="eye-window"><div class="try-content"><div class="try-left-box">`
        windowHtml += `<div class="title-box">
                    <div class="title">${$.mage.__('EYECEDAR')}</div>
                    <div class="sub-title">${$.mage.__('Try on glasses')}</div>
                    <div class="pd-box" style="display: flex;margin-top: 20px;">
                        <label class="label" style="display: block;margin-right: 10px">${$.mage.__('PD')}</label>
                        <input type="number" class="pd-text" value="62">
                    </div>
                </div>
                </div>
                <div class="try-right-box">
                <i class="eye-close"></i>
                <div class="position-img-box">
                    <canvas id="eye-position" width="480" height="480" class="eye-position"></canvas>
                    <div class="red-btn left-eye" id="left-eyes"></div>
                    <div class="red-btn right-eye" id="right-eyes"></div>
                </div>
                <div class="toolbar-box">
                    <button type="button" class="try-glass">${$.mage.__('TRY ON GLASSES')}</button>
                </div>
                </div>
                </div>
                </div>`
        $("body").append(windowHtml)
        let canvas = document.getElementById('eye-position');
        let ctx = canvas.getContext('2d');
        ctx.clearRect(0,0,480,480);
        var img = new Image();
        img.src = url;
        img.onload = function() {
            if(img.width <= 480 && img.height <= 480) {
                var left = (480 - img.width)/2,
                    top = (480 - img.width)/2;
                ctx.drawImage(img,left,top,480, 480);
            }
            else {
                if(img.width > 480 && img.height <= 480) {
                    var top = (480 - 480/img.width*img.height)/2
                    ctx.drawImage(img,0,top,480, 480);
                }
                else if(img.width <= 480 && img.height > 480) {
                    var left = (480 - img.width)/2
                    ctx.drawImage(img,left,0,480, img.height);
                }
                else {
                    if(480*img.height/img.width > 480) {
                        ctx.drawImage(img,0,0,480, 480*img.height/img.width);
                    }
                    else {
                        ctx.drawImage(img,0,0,480, 480);
                    }
                }
            }
        }
        mouseDomEventEyeByPc()
    }
    // 获取mobile眼睛定点
    function getEyePositionMobile(url) {
        let windowHtml = `<div class="alert-window try-on-box" id="eye-window"><div class="try-content">`
        windowHtml += `<div class="title-box">
                    <div class="title">${$.mage.__('EYECEDAR')}</div>
                    <div class="sub-title">${$.mage.__('Try on glasses')}</div>
                    <div class="pd-box" style="display: flex;margin-top: 20px;">
                        <label class="label" style="display: block;margin-right: 10px">${$.mage.__('PD')}</label>
                        <input type="number" class="pd-text" value="62">
                    </div>
                </div>
                <i class="eye-close"></i>
                <div class="position-img-box">
                    <canvas id="eye-position" width="480" height="480" class="eye-position"></canvas>
                    <div class="red-btn left-eye" id="left-eyes"></div>
                    <div class="red-btn right-eye" id="right-eyes"></div>
                </div>
                <div class="toolbar-box">
                    <button type="button" class="try-glass">${$.mage.__('TRY ON GLASSES')}</button>
                </div>
                </div>
                </div>`
        $("body").append(windowHtml)
        let canvas = document.getElementById('eye-position');
        let ctx = canvas.getContext('2d');
        ctx.clearRect(0,0,480,480);
        var img = new Image();
        img.src = url;
        img.onload = function() {
            if(img.width <= 480 && img.height <= 480) {
                var left = (480 - img.width)/2,
                    top = (480 - img.width)/2;
                ctx.drawImage(img,left,top,480, 480);
            }
            else {
                if(img.width > 480 && img.height <= 480) {
                    var top = (480 - 480/img.width*img.height)/2
                    ctx.drawImage(img,0,top,480, 480);
                }
                else if(img.width <= 480 && img.height > 480) {
                    var left = (480 - img.width)/2
                    ctx.drawImage(img,left,0,480, img.height);
                }
                else {
                    if(480*img.height/img.width > 480) {
                        ctx.drawImage(img,0,0,480, 480*img.height/img.width);
                    }
                    else {
                        ctx.drawImage(img,0,0,480, 480);
                    }
                }
            }
        }
        mouseDomEventEyeByMobile()
    }
    // 眼睛位置
    let lEyeX=0;
    let lEyeY=0;
    let lEyeL=0;
    let lEyeT=0;
    let rEyeX=0;
    let rEyeY=0;
    let rEyeL=0;
    let rEyeT=0;
    let lEyeDown = false
    let rEyeDown = false
    // PC端 眼定点拖拽 鼠标事件
    function mouseDomEventEyeByPc(){
        // 眼镜 dom
        let eyeDom = document.getElementById('left-eyes');
        let rEyeDom = document.getElementById('right-eyes');
        // 眼镜拖拽 鼠标移动
        window.onmousemove = function(e) {
            if(lEyeDown) {
                //获取x和y
                let nx = e.clientX;
                let ny = e.clientY;
                //计算移动后的左偏移量和顶部的偏移量
                let nl = nx - (lEyeX - lEyeL);
                let nt = ny - (lEyeY - lEyeT);
                //设置样式
                eyeDom.style.left = nl + 'px';
                eyeDom.style.top = nt + 'px';
            }
            if (rEyeDown) {
                let nx = e.clientX;
                let ny = e.clientY;
                //计算移动后的左偏移量和顶部的偏移量
                let nl = nx - (rEyeX - rEyeL);
                let nt = ny - (rEyeY - rEyeT);
                //设置样式
                rEyeDom.style.left = nl + 'px';
                rEyeDom.style.top = nt + 'px';
            }
        }
        // 眼镜拖拽 鼠标按下事件
        eyeDom.onmousedown = function(e) {
            e.preventDefault()
            //获取x坐标和y坐标
            lEyeX = e.clientX;
            lEyeY = e.clientY;
            //获取左部和顶部的偏移量
            lEyeL = eyeDom.offsetLeft;
            lEyeT = eyeDom.offsetTop;
            //开关打开
            lEyeDown = true;
            //设置样式
            eyeDom.style.cursor = 'move';
        }
        // 眼镜拖拽 鼠标抬起事件
        eyeDom.onmouseup = function() {
            //开关关闭
            lEyeDown = false;
            //设置样式
            eyeDom.style.cursor = 'default';
        }
        // 眼镜拖拽 鼠标按下事件
        rEyeDom.onmousedown = function(e) {
            e.preventDefault()
            //获取x坐标和y坐标
            rEyeX = e.clientX;
            rEyeY = e.clientY;
            //获取左部和顶部的偏移量
            rEyeL = rEyeDom.offsetLeft;
            rEyeT = rEyeDom.offsetTop;
            //开关打开
            rEyeDown = true;
            //设置样式
            rEyeDom.style.cursor = 'move';
        }
        // 眼镜拖拽 鼠标抬起事件
        rEyeDom.onmouseup = function() {
            //开关关闭
            rEyeDown = false;
            //设置样式
            rEyeDom.style.cursor = 'default';
        }
    }
    //mobile端 眼定点拖拽 鼠标事件
    function mouseDomEventEyeByMobile(){
        var _x_start,_y_start,_x_move,_y_move,left_start,top_start;
        document.getElementById("left-eyes").addEventListener("touchstart",function(e){
            _x_start=e.touches[0].pageX;
            _y_start=e.touches[0].pageY;
            left_start=$("#left-eyes").css("left");
            top_start=$("#left-eyes").css("top");
        })
        document.getElementById("left-eyes").addEventListener("touchmove",function(e){
            e.preventDefault()
            _x_move=e.touches[0].pageX;
            _y_move=e.touches[0].pageY;
            $("#left-eyes").css("left",parseFloat(_x_move)-parseFloat(_x_start)+parseFloat(left_start)+"px");
            $("#left-eyes").css("top",parseFloat(_y_move)-parseFloat(_y_start)+parseFloat(top_start)+"px");
        })
        var e_x_start,e_y_start,e_x_move,e_y_move,e_left_start,e_top_start;
        document.getElementById("right-eyes").addEventListener("touchstart",function(e){
            e_x_start=e.touches[0].pageX;
            e_y_start=e.touches[0].pageY;
            e_left_start=$("#right-eyes").css("left");
            e_top_start=$("#right-eyes").css("top");
        })
        document.getElementById("right-eyes").addEventListener("touchmove",function(e){
            e.preventDefault()
            e_x_move=e.touches[0].pageX;
            e_y_move=e.touches[0].pageY;
            $("#right-eyes").css("left",parseFloat(e_x_move)-parseFloat(e_x_start)+parseFloat(e_left_start)+"px");
            $("#right-eyes").css("top",parseFloat(e_y_move)-parseFloat(e_y_start)+parseFloat(e_top_start)+"px");
        })
    }
    //获取photo 帮助弹窗
    $(document).on("click",'.note-info .help-icon',function (){
        let _html = "";
        _html += `<div class="help-wrapper"><div class="help-content"><img src="/media/tryon/help.jpg"><button type="button" class="ok">${$.mage.__("ok,I Know")}</button></div></div>`
        $(".try-on-box .try-content").append(_html)
    })
    //关闭帮助弹窗
    //获取photo 帮助弹窗
    $(document).on("click",'.help-content .ok',function (){
        $(".help-wrapper").remove()
    })
    /* 筛选交互逻辑 */
    class _productFilter {
        constructor() {}
        init (option) {
            this.timer = null;
            this.productUl = document.getElementById(option.productFilter_title);
            this.productCon = document.getElementById(option.productFilter_content);
            this.contentLi = this.productCon.querySelectorAll(option.li);
            this.contentActive = option.contentActive;
            this.mouseEvent();
        }
        mouseEvent () {
            let self = this;
            this.productUl.onmouseover = function(e) {
                self.clearTime(e);
            };
            this.productUl.onmouseout = function() {
                self.setTime();
            };
            this.productCon.onmouseover = function(e) {
                self.clearTime(e);
            };
            this.productCon.onmouseout = function() {
                self.setTime();
            };
        }
        clearTime (e) {
            let self = this;
            if (self.timer) clearTimeout(self.timer);
            self.mouseOver(e);
        }
        setTime () {
            let self = this;
            self.timer = setTimeout(function() {
                self.removeClass()
            }, 50);
        }
        mouseOver (e) {
            let self = this;
            if (e.target.tagName.toLowerCase() === 'li') {
                let num = parseInt(e.target.dataset.index);
                self.removeClass();
                self.contentLi[num].classList.add(self.contentActive);
            }
        }
        removeClass () {
            if (this.contentLi && this.contentLi.length) {
                for (let i = 0; i < this.contentLi.length; i++) {
                    this.contentLi[i].classList.remove(this.contentActive);
                }
            }
        }
    }
    // 获取筛选数据并初始化
    getProductFilter();
    // 获取筛数据
    function getProductFilter() {
        var index = '';
        $.ajax({
            url: '/api/product/filter',
            type: 'post',
            data: {},
            dataType: 'json',
            beforeSend: function() {
                $('.mask').addClass('flex');
            },
            success: function(res) {
                renderFilter(res.data);
                const productFilter = new _productFilter();
                productFilter.init({
                    productFilter_title: 'productFilter_title',
                    productFilter_content: 'productFilter_content',
                    li: '.li',
                    contentActive: 'contentActive'
                });
                layui.use(['form'], function() {
                    var form = layui.form;
                    $('.mask').removeClass('flex');
                    form.render('checkbox', 'test1');
                });
            }
        })
    }
    // 渲染HTML元素
    function renderProduct(data) {
        const productList = document.getElementById('productList');
        const showMore_box = document.querySelector('.showMore_box');
        const wishData = JSON.parse(localStorage.getItem('wishData'));
        if (data && data.length) {
            let _template = '';
            for (let i = 0; i < data.length; i++) {
                let _template1 = '';
                let _template2 = '';
                let _template3 = '';
                let _template4 = '';
                let _template5 = '';
                let imgs = [];
                let _colorArr = [];
                let isAddFav = false;
                if (data[i].imgs && data[i].imgs.length) {
                    for (let x = 0; x < data[i].imgs.length; x++) {
                        if (!imgs) {
                            if (data[i].imgs[x].alt === null) continue;
                            imgs.push(data[i].imgs[x]);
                            _colorArr.push(data[i].imgs[x].alt.toLowerCase());
                        } else if (data[i].imgs[x].alt !== null && _colorArr.indexOf(data[i].imgs[x].alt.toLowerCase().trim()) === -1) {
                            imgs.push(data[i].imgs[x]);
                            _colorArr.push(data[i].imgs[x].alt.toLowerCase().trim());
                        }
                    }
                }
                if(show_mode != 'product') {
                    _template1 = `<li class="productionList_li static p15">
									<a href="${data[i].url}" class="wrapper p15">
										<ul class="productionList_img">`;
                }
                else {
                    _template1 = `<li class="productionList_li p15">
									<a href="${data[i].url}" class="wrapper p15">
										<ul class="productionList_img">`;
                }
                /* 遍历产品图片 start */
                if (imgs.length) {
                    for (let j = 0; j < imgs.length; j++) {
                        if(show_mode != 'product') {
                            _template2 += `<li class="productionList_img_li" data-color="${imgs[j].alt.toLowerCase()}"><img src="#" data-src="${imgs[j].url}" class="img">`;
                            if(data[i].vm.length > 0) {
                                _template2 += `<img src="${data[i].vm[j]}" data-src="${data[i].vm[j]}" class="gimg" />`
                            }
                            else {
                                _template2 += `<img src="${glasses[0]}" data-src="${glasses[0]}" class="gimg" />`
                            }
                            if(j === 0) {
                                // _template2 += `<li class="productionList_img_li" data-color="${imgs[j].alt.toLowerCase()}"><img src="${glasses[0]}" data-src="${glasses[0]}" class="img">`;
                                _template2 += `<img id="headCanvas-${data[i].id}-${j}" class="product-try-right-head" src="${currentAvtar}" data-src="${currentAvtar}" /></li>`
                            }
                            else {
                                _template2 += `<img id="headCanvas-${data[i].id}-${j}" class="product-try-right-head" src="${modeMedia[currentAvtar].url}" data-src="${modeMedia[currentAvtar].url}" /></li>`
                            }
                        }
                        else {
                            if(j === 0) {
                                _template2 += `<li class="productionList_img_li static" data-color="${imgs[j].alt.toLowerCase()}"><img src="${imgs[j].url}" data-src="${imgs[j].url}" class="img"></li>`;
                            }
                            else {
                                _template2 += `<li class="productionList_img_li static" data-color="${imgs[j].alt.toLowerCase()}"><img src="#" data-src="${imgs[j].url}" class="img"></li>`;
                            }
                        }
                    }
                } else {
                    _template2 += `<li class="productionList_img_li static" data-color="black"><img src="/media/tmp/image.png" data-src="/media/tmp/image.png" class="img">`
                }

                /* 遍历产品图片 end */
                /* 遍历产品名称 start */
                _template3 = `</ul><div class="productionList_li_content"><div class="title ptb10">${data[i].name}</div><ul class="circleColor ptb10">`;
                /* 遍历产品名称 end */
                /* 遍历产品颜色按钮 start */
                for (let k = 0; k < data[i].options.length; k++) {
                    _template4 += `<li class="circleColor_li" data-color="${data[i].options[k].value_title.toLowerCase()}"><img class="img" src="${data[i].options[k].value_img}" alt=""></li>`;
                }
                /* 遍历产品颜色按钮 end */
                /* 判断显示折扣金额标签 start */
                if (data[i].finalPrice === data[i].price) {
                    _template5 = `</ul><div class="price ptb10"><div class="price_new">$${data[i].price}`
                } else {
                    _template5 = `</ul><div class="price ptb10"><div class="price_new">$${data[i].finalPrice}<del class="price_old">$${data[i].price}</del>`
                }
                if (wishData && wishData.length) {
                    for (let j = 0; j < wishData.length; j++) {
                        if (wishData[j].id === data[i].id) {
                            isAddFav = true;
                            break;
                        }
                    }
                }
                /* 判断显示折扣金额标签 end */
                if (isAddFav) {
                    _template5 += `</div><div class="_favourites"><span class="glyphicon glyphicon-heart" aria-hidden="true"></span></div></div>`;
                } else {
                    _template5 += `</div><div class="_favourites"><span class="glyphicon glyphicon-heart-empty" aria-hidden="true"></span></div></div>`;
                }
                _template5 +=  `<ul class="glasses-box">`
                if(data[i].vm.length > 0) {
                    data[i].vm.forEach(item => {
                        _template5 += `<li><img src="#" data-src="${item}"/></li>`
                    })
                }
                else {
                    glasses.forEach(item => {
                        _template5 += `<li><img src="#" data-src="${item}"/></li>`
                    })
                }
                _template5 += `</ul><div class="btn-wrapper"><button type="button" class="tryon">${$.mage.__('Try On')}</span></button><button type="button" class="shop-now">${$.mage.__('Shop Now')}</button></div></div></a></li>`
                _template += _template1 + _template2 + _template3 + _template4 + _template5;
            }
            productList.innerHTML = _template;
            showMore_box.classList.add('contentActive');
        } else {
            productList.innerHTML = `<li style="width:100%; text-align:center;font-size: 18px; color:#ccc;font-weight:bold;margin:50px 0;">${$.mage.__("No Nothing Data")}</li>`;
            showMore_box.classList.remove('contentActive');
        }
    }
    //try on 自动佩戴
    function alertAutoMatch(num,ids) {
        const that = $(`#${ids}`)
        let objId = ids
        that.attr('src',modeMedia[num].url);
        const glassesobj = $("#glassesMove");
        // 获取图片DOM宽高
        let _widthDom = that.parent(".try-right-head-box").width();
        setHead(num,glassesobj,_widthDom)
        glassesobj.css("transform","scale(1) rotate(0deg)")
    }
    //自动佩戴
    function autoMatch(num,ids) {
        if(ids) {
            const that = $(`#${ids}`)
            let objId = ids
            let autoUrl = modeMedia[num].url ? modeMedia[num].url : modeMedia[currentAvtar].url
            that.attr('data-src',autoUrl);
            that.attr('src',autoUrl);
            const glassesobj = that.prev(".gimg");
            // 获取图片DOM宽高
            let _widthDom = that.parent(".productionList_img_li").width();
            setHead(num,glassesobj,_widthDom)
        }
        else {
            let canvasObj = $('img[id^="headCanvas-"]')
            for(var i = 0;i  < canvasObj.length;i++) {
                const that = canvasObj.eq(i)
                const glassesobj = that.prev(".gimg");
                let objId = that.attr("id")
                let _i = 0
                let autoUrl = modeMedia[num].url ? modeMedia[num].url : modeMedia[currentAvtar].url
                that.attr('data-src',autoUrl);
                if(that.parent(".productionList_img_li").hasClass("productionListActive")) {
                    that.attr('src',autoUrl);
                    // 获取图片DOM宽高
                    let _widthDom = that.parent(".productionList_img_li").width();
                    setHead(num,glassesobj,_widthDom)
                }
            }
        }
    }
    // 镜框定位
    function setHead(num,glassesobj,_widthDom) {
        var glassesLeft = modeMedia[num].left/480*_widthDom,
            glassesWidth = modeMedia[num].width/480*_widthDom,
            glassesTop = modeMedia[num].top/480*_widthDom
        glassesobj.css("width",glassesWidth+'px')
        glassesobj.css("left",glassesLeft+'px')
        glassesobj.css("top",glassesTop+'px')
    }
    // 眼镜滑块 鼠标事件
    function mouseDomEventBySlider(){
        // 缩放滑块
        let scaleDom = $('.try-scale .try-swiper-input')[0];
        // 缩放滑块
        let rotateDom = $('.try-rotate .try-swiper-input')[0];
        // 缩放dom 监听事件
        scaleDom.addEventListener("input",function(e) {
            iconMove($('.try-scale .try-swiper-input').val(),'scale');
            if(_isPc){
            }
        },false);
        // 旋转dom 监听事件
        rotateDom.addEventListener("input",function(e) {
            iconMove($('.try-rotate .try-swiper-input').val(),'rotate');
            if(_isPc){
            }
        },false);
    }
    // 眼镜缩放尺寸
    function tryOnScale(scale){
        // 获取已旋转情况
        let _rotate=$('.try-on-box .try-right-glasses').attr('data-rotate');
        _rotate=_rotate?_rotate:0;
        // 获取眼镜图片
        let _width=$('.try-on-box .try-right-glasses').css('width');
        _width=changeNumber(_width)
        // 获取已缩放情况
        let _scale=$('.try-on-box .try-right-glasses').attr('data-scale');
        let _newScale=parseFloat(((scale/_width).toFixed(2)));
        // 缩放
        _newScale=(_scale?parseFloat(_scale):1)+_newScale;
        // 缩放上限是2倍
        if(_newScale>=2){
            _newScale=2
        }else if(_newScale<=0){
            _newScale=0
        }
        // 眼镜图片处理
        $('.try-on-box .try-right-glasses').css({
            transform:'scale('+_newScale+') rotate('+_rotate+'deg)',
            '-ms-transform':'scale('+_newScale+') rotate('+_rotate+'deg)',
            '-moz-transform':'scale('+_newScale+') rotate('+_rotate+'deg)',
            '-webkit-transform':'scale('+_newScale+') rotate('+_rotate+'deg)',
            '-o-transform':'scale('+_newScale+') rotate('+_rotate+'deg)',
        })
        $('.try-on-box .try-right-glasses').attr('data-scale',_newScale.toFixed(2));
    }
    // 眼镜旋转角度
    function tryOnRotateImg(rotate){
        // 获取已缩放情况
        let _scale=$('.try-on-box .try-right-head').attr('data-scale');
        _scale=_scale?_scale:1;
        // 获取已旋转情况
        let _rotate=$('.try-on-box .try-right-head').attr('data-rotate');
        let _newRotate=0;
        _newRotate=(_rotate?parseFloat(_rotate):0)+parseFloat(rotate);
        if(_newRotate>=360){
            _newRotate=_newRotate-360;
            let _num=parseFloat((_newRotate/360*50)+50);
            $('.try-rotate .try-swiper-input').val(_num);
            document.styleSheets[0].addRule('.try-rotate .try-swiper-input::-webkit-slider-runnable-track','background: linear-gradient(to right,#59C9FB 0,#59C9FB '+_num+'%,white 0,white 100%)');
        }else if(_newRotate<=-360){
            _newRotate=_newRotate+360;
            let _num=parseFloat((_newRotate/360*50)+50);
            $('.try-rotate .try-swiper-input').val(_num);
            document.styleSheets[0].addRule('.try-rotate .try-swiper-input::-webkit-slider-runnable-track','background: linear-gradient(to right,#59C9FB 0,#59C9FB '+_num+'%,white 0,white 100%)');
        }

        // 图片处理
        $('.try-on-box .try-right-head').css({
            transform:'scale('+_scale+') rotate('+_newRotate+'deg)',
            '-ms-transform':'scale('+_scale+') rotate('+_newRotate+'deg)',
            '-moz-transform':'scale('+_scale+') rotate('+_newRotate+'deg)',
            '-webkit-transform':'scale('+_scale+') rotate('+_newRotate+'deg)',
            '-o-transform':'scale('+_scale+') rotate('+_newRotate+'deg)',
        })

        $('.try-on-box .try-right-head').attr('data-rotate',_newRotate);
    }
    // 眼镜角度90度 旋转
    $(document).on('click','.try-on-box .try-right-head-tool',function(){
        // 滑块修改
        if(_isPc){
            let _value=$('.try-rotate .try-swiper-input').val();
            $('.try-rotate .try-swiper-input').val(parseFloat(_value)-12.5);
            iconMove(parseFloat(_value)-12.5,'rotate',true);
        }else{
            tryOnRotateImg(90,true);
        }
    })
    // 眼镜尺寸大小 放大
    $(document).on('click','.icon-add',function(){
        // 获取眼镜图片
        let _width=$('.try-on-box .try-right-glasses').css('width');
        _width=changeNumber(_width);
        // 获取已缩放情况
        let _scale=$('.try-on-box .try-right-glasses').attr('data-scale');
        _scale=_scale?_scale:1;
        // 图片的真实宽度
        _width=_width/_scale;
        // 已有滑块值
        let _value=$('.try-scale .try-swiper-input').val();
        // 修改后的滑块值
        _value=((15/parseFloat(_width)+parseFloat(_scale))*50).toFixed(1);
        $('.try-scale .try-swiper-input').val(_value);
        iconMove(parseFloat(_value),'scale');
    })
    // 眼镜尺寸大小 缩小
    $(document).on('click','.icon-narrow',function(){
        // 获取眼镜图片
        let _width=$('.try-on-box .try-right-glasses').css('width');
        _width=changeNumber(_width);
        // 获取已缩放情况
        let _scale=$('.try-on-box .try-right-glasses').attr('data-scale');
        _scale=_scale?_scale:1;
        // 图片的真实宽度
        _width=_width/_scale;
        // 已有滑块值
        let _value=$('.try-scale .try-swiper-input').val();
        // 修改后的滑块值
        _value=((-(15/parseFloat(_width))+parseFloat(_scale))*50).toFixed(1);
        $('.try-scale .try-swiper-input').val(_value);
        iconMove(parseFloat(_value),'scale');
    })
    // 眼镜角度按钮 向左旋转
    $(document).on('click','.icon-turn-left',function(){
        // tryOnRotate(-2);
        // 获取已旋转情况
        let _rotate=$('.try-on-box .try-right-glasses').attr('data-rotate');
        _rotate=_rotate?_rotate:0;
        // 已有滑块值
        let _value=$('.try-rotate .try-swiper-input').val();
        // 修改后的滑块值
        _value=(-2+parseFloat(_rotate))/360*50+50
        $('.try-rotate .try-swiper-input').val(_value);
        iconMove(parseFloat(_value),'rotate');
    })
    // 眼镜角度按钮 向右旋转
    $(document).on('click','.icon-turn-right',function(){
        // tryOnRotate(2);
        // 获取已旋转情况
        let _rotate=$('.try-on-box .try-right-glasses').attr('data-rotate');
        _rotate=_rotate?_rotate:0;
        // 已有滑块值
        let _value=$('.try-rotate .try-swiper-input').val();
        // 修改后的滑块值
        _value=(2+parseFloat(_rotate))/360*50+50
        $('.try-rotate .try-swiper-input').val(_value);
        iconMove(parseFloat(_value),'rotate');
    })
    // 眼镜旋转角度
    function tryOnRotate(rotate){
        // 获取已缩放情况
        let _scale=$('.try-on-box .try-right-glasses').attr('data-scale');
        _scale=_scale?_scale:1;
        // 获取已旋转情况
        let _rotate=$('.try-on-box .try-right-glasses').attr('data-rotate');
        let _newRotate=0;
        _newRotate=(_rotate?parseFloat(_rotate):0)+parseFloat(rotate);
        if(_newRotate>=360){
            _newRotate=_newRotate-360;
            let _num=parseFloat((_newRotate/360*50)+50);
            $('.try-rotate .try-swiper-input').val(_num);
            document.styleSheets[0].addRule('.try-rotate .try-swiper-input::-webkit-slider-runnable-track','background: linear-gradient(to right,#59C9FB 0,#59C9FB '+_num+'%,white 0,white 100%)');
        }else if(_newRotate<=-360){
            _newRotate=_newRotate+360;
            let _num=parseFloat((_newRotate/360*50)+50);
            $('.try-rotate .try-swiper-input').val(_num);
            document.styleSheets[0].addRule('.try-rotate .try-swiper-input::-webkit-slider-runnable-track','background: linear-gradient(to right,#59C9FB 0,#59C9FB '+_num+'%,white 0,white 100%)');
        }

        // 图片处理
        $('.try-on-box .try-right-glasses').css({
            transform:'scale('+_scale+') rotate('+_newRotate+'deg)',
            '-ms-transform':'scale('+_scale+') rotate('+_newRotate+'deg)',
            '-moz-transform':'scale('+_scale+') rotate('+_newRotate+'deg)',
            '-webkit-transform':'scale('+_scale+') rotate('+_newRotate+'deg)',
            '-o-transform':'scale('+_scale+') rotate('+_newRotate+'deg)',
        })

        $('.try-on-box .try-right-glasses').attr('data-rotate',_newRotate);
    }
    // 眼镜 位置
    function tryMove(type,displacement){
        let _top=$('.try-on-box .try-right-glasses').css('top');
        _top=parseFloat(_top)*0.75;
        let _left=$('.try-on-box .try-right-glasses').css('left');
        _left=parseFloat(_left)*0.75;
        if(type=='up'){
            $('.try-on-box .try-right-glasses').css('top',(parseFloat(_top)-parseFloat(displacement)).toFixed(2)+'pt')
        }else if(type=='down'){
            $('.try-on-box .try-right-glasses').css('top',(parseFloat(_top)+parseFloat(displacement)).toFixed(2)+'pt')
        }else if(type=='left'){
            $('.try-on-box .try-right-glasses').css('left',(parseFloat(_left)-parseFloat(displacement)).toFixed(2)+'pt')
        }else if(type=='right'){
            $('.try-on-box .try-right-glasses').css('left',(parseFloat(_left)+parseFloat(displacement)).toFixed(2)+'pt')
        }
    }
    // 旋转，缩放 按钮的拖拽功能
    function iconMove(num,type,img=false) {
        // 获取已旋转情况
        let _rotate=$('.try-on-box .try-right-glasses').attr('data-rotate');
        _rotate=_rotate?_rotate:0;
        // 获取眼镜图片
        let _width=$('.try-on-box .try-right-glasses').css('width');
        _width=changeNumber(_width)
        // 获取已缩放情况
        let _scale=$('.try-on-box .try-right-glasses').attr('data-scale');
        _scale=_scale?_scale:1;
        // 样式修改
        if(type=='scale'){
            document.styleSheets[0].addRule('.try-scale .try-swiper-input::-webkit-slider-runnable-track','background: linear-gradient(to right,#59C9FB 0,#59C9FB '+num+'%,white 0,white 100%)');
            // 尺寸修改
            let _value=((num/50-_scale)*_width).toFixed(2)
            tryOnScale(_value);
        }else if(type=='rotate'){
            document.styleSheets[0].addRule('.try-rotate .try-swiper-input::-webkit-slider-runnable-track','background: linear-gradient(to right,#59C9FB 0,#59C9FB '+num+'%,white 0,white 100%)');
            let _value=(((num-50)/50*360-_rotate)).toFixed(2)
            if(img){
                tryOnRotateImg(90);
            }else{
                tryOnRotate(_value,img);
            }
        }
    }
    // PC端 眼镜拖拽 鼠标事件
    function mouseDomEventGlassByPc(){
        // 眼镜 dom
        let glassDom = document.getElementById('glassesMove');
        // 眼镜拖拽 鼠标移动
        window.onmousemove = function(e) {
            if (glassIsDown == false) {
                return;
            }
            //获取x和y
            let nx = e.clientX;
            let ny = e.clientY;
            //计算移动后的左偏移量和顶部的偏移量
            let nl = nx - (glassX - glassL);
            let nt = ny - (glassY - glassT);
            //设置样式
            glassDom.style.left = nl + 'px';
            glassDom.style.top = nt + 'px';
        }
        // 眼镜拖拽 鼠标按下事件
        glassDom.onmousedown = function(e) {
            e.preventDefault()
            //获取x坐标和y坐标
            glassX = e.clientX;
            glassY = e.clientY;
            //获取左部和顶部的偏移量
            glassL = glassDom.offsetLeft;
            glassT = glassDom.offsetTop;
            //开关打开
            glassIsDown = true;
            //设置样式
            glassDom.style.cursor = 'move';
        }
        // 眼镜拖拽 鼠标抬起事件
        glassDom.onmouseup = function() {
            //开关关闭
            glassIsDown = false;
            //设置样式
            glassDom.style.cursor = 'default';
        }
    }
    // 移动端 眼镜拖拽 鼠标事件
    function mouseDomEventGlassByMobile(){
        var _x_start,_y_start,_x_move,_y_move,left_start,top_start;
        document.getElementById("glassesMove").addEventListener("touchstart",function(e){
            _x_start=e.touches[0].pageX;
            _y_start=e.touches[0].pageY;
            left_start=$("#glassesMove").css("left");
            top_start=$("#glassesMove").css("top");
        })
        document.getElementById("glassesMove").addEventListener("touchmove",function(e){
            e.preventDefault()
            _x_move=e.touches[0].pageX;
            _y_move=e.touches[0].pageY;
            $("#glassesMove").css("left",parseFloat(_x_move)-parseFloat(_x_start)+parseFloat(left_start)+"px");
            $("#glassesMove").css("top",parseFloat(_y_move)-parseFloat(_y_start)+parseFloat(top_start)+"px");
        })
        //阻止浏览器下拉事件
        // document.body.addEventListener('touchmove',function (event) {event.preventDefault();},{passive: false});
    }
    // 渲染筛选数据
    function renderFilter(filterData) {
        if (filterData && filterData.length) {
            let template1 = '';
            let template2 = '';
            let type = '';
            for (let i = 0; i < filterData.length; i++) {
                template1 += `<li class="li p5" data-index="${i}">${filterData[i].label}</li>`;
                if (filterData[i].options && filterData[i].options.length) {
                    let _template = `<li class="li p30" data-index="${i}">`;
                    for (let j = 0; j < filterData[i].options.length; j++) {
                        _template += `<input type="checkbox" lay-filter="filterparams" name="${filterData[i].code}" title="${filterData[i].options[j].label}" class="filterparams" lay-skin="primary" value="${filterData[i].options[j].id}">`;
                        if (filterData[i].code === 'custom_color') {
                            _template += `<img src="${filterData[i].options[j].src}" class="img">`;
                        }
                        type = filterData[i].code;
                    }
                    template2 += _template + `<span class="ml50 checkall"><input lay-skin="primary" type="checkbox" id="checkall" name="${type}" lay-filter="c_all" value="checkall"/>All | Clear All</span></li>`
                }
            }
            const productFilter_title = document.getElementById('productFilter_title');
            const productFilter_content = document.getElementById('productFilter_content');
            productFilter_title.innerHTML = template1;
            productFilter_content.innerHTML = template2;
        }
    }
    // 获取产品列表数据请求
    function load_data(option, isMore = false, loading = false, isProduct = true) {
        var _option = {
            category,
            sex,
            page: 1,
            size: 48
        };
        _option = Object.assign(_option, option);
        var index = '';
        $.ajax({
            url: '/api/product/listset',
            type: 'post',
            data: _option,
            dataType: 'json',
            beforeSend: function() {
                if(loading) {
                    $('.mask').addClass('flex bgLoading');
                } else {
                    $('.mask').addClass('flex');
                }
            },
            success: function(res) {
                if(loading) {
                    $('.mask').removeClass('flex bgLoading');
                } else {
                    $('.mask').removeClass('flex');
                }
                if (res.product && res.product.length) {
                    if (isMore) {
                        let newArr = curData.concat(res.product);
                        renderProduct(newArr);
                        curData = newArr;
                    } else {
                        renderProduct(res.product);
                        curData = res.product;
                    }
                    total = res.total_page;
                    if (isProduct) {
                        const _productList = new productFun();
                        _productList.initClick({
                            productionListEle: '.productionList_li',
                            clickEle: '.circleColor_li',
                            changeEle: '.productionList_img_li',
                            clickClass: '.circleColorActive',
                            changeClass: '.productionListActive',
                            _favourites: '._favourites'
                        }, res.product);
                    } else {
                        const _productList = new productFun();
                        _productList.initClick({
                            productionListEle: '.productionList_li',
                            clickEle: '.circleColor_li',
                            changeEle: '.productionList_img_li',
                            clickClass: '.circleColorActive',
                            changeClass: '.productionListActive',
                            _favourites: '._favourites'
                        }, res.product);
                    }
                    const reg = /\.+/g;
                    const bannerImg = document.getElementById('bannerImg');
                    if (reg.test(res.category_img)) {
                        bannerImg.setAttribute('src', res && res.category_img);
                    } else {
                        bannerImg.setAttribute('src', '/media/catalog/category/_New-arrivals_03_1.jpg');
                    }
                    $('#bannerImg').load(function(){
                        bannerImg.className = 'img';
                        $(".article").removeClass("none")
                    })
                }
            }
        })
    }
    btn.addEventListener('click', function() {
        if (productConfig.page < total) {
            productConfig.page++;
            load_data(productConfig, true, false, false);
        } else {
            btn.innerText = `${$.mage.__('No Nothing')}`
        }
    });
    /* 获取筛选相关数据 start */
    layui.use('form', function() {
        var form = layui.form;
        form.render('checkbox', 'test1');
        form.on('checkbox(filterparams)', function(data) {
            // 把选择的属性生成一个对象，
            let name = data.elem.getAttribute('name');
            let _id = data.value;
            if (data.elem.checked) {
                // 添加选项到对象 obj:{red: 84}
                if (option.hasOwnProperty(name)) {
                    let arr = option[name].split(',');
                    if (arr.length && arr.indexOf(_id) === -1) {
                        arr.push(_id);
                        option[name] = arr.join(',');
                        // 调用请求
                        load_data(option);
                    }
                    return;
                } else {
                    option[name] = _id;
                    // 调用请求
                    load_data(option);
                }
            } else {
                if (option.hasOwnProperty(name)) {
                    let arr = option[name].split(',');
                    if (arr.length && arr.indexOf(_id) !== -1) {
                        let index = arr.indexOf(_id);
                        arr.splice(index, 1);
                        option[name] = arr.join(',');
                        if (!option[name]) delete option[name];
                        // 调用请求
                        load_data(option);
                    }
                }
            }
        });
        //点击全选, 勾选
        form.on('checkbox(c_all)', function(data) {
            const _dom = data.elem.parentNode.parentNode;
            const filterparams = _dom.querySelectorAll('.filterparams');
            const name = data.elem.getAttribute('name');
            let arr = [];
            for (let i = 0; i < filterparams.length; i++) {
                filterparams[i].checked = data.elem.checked;
                if (data.elem.checked) {
                    arr.push(filterparams[i].value);
                }
            }
            if (!data.elem.checked) {
                delete option[name];
            } else {
                option[name] = arr.join(',');
            }
            form.render('checkbox');
            load_data(option);
        });
    });
    /* 获取筛选相关数据 end */
})
